import { Button, DatePicker, Form, Input, InputNumber, message, Radio, Space, Spin, Switch } from "antd";
import locale from "antd/es/date-picker/locale/zh_CN";
import moment from "moment";
import { useEffect, useState } from "react";
import { getCategoryAPI } from "../../api";
import { IAccount, AccountType, ICategory } from "../../interface";

interface AccountCommitProps {
    account?: IAccount
    submitFrom: (data: IFormData) => void
    cancel: () => void
}
export interface IFormData {
    date_time: moment.Moment
    account_id: number
    account_type: AccountType
    amount: number
    category_id: number
    notes: string
}

const initFormData: IFormData = {
    account_id: 0,
    account_type: AccountType.expend, // true支出, false收入
    amount: 0,
    category_id: 0,
    date_time: moment(new Date()),
    notes: '',
};

const AccountCommit: React.FC<AccountCommitProps> = (props) => {

    let { account } = props;

    const [categoryLoading, setCategoryLoading] = useState(false);
    
    // 钩子可以数据绑定
    const [form] = Form.useForm();
    const [formData, setFormData] = useState<IFormData>(initFormData);

    // 获取所有分类
    useEffect(() => {
        setCategoryLoading(true);
        getCategoryAPI()
        .then(res => {
            if (res.data.code === 0) {
                setCategory(res.data.data)
            } else {
                throw new Error(res.data.message);
            }
        })
        .catch(e => {
            console.log('category获取发生错误')
            console.log(e)
            message.error(e.message);
        })
        .finally(() => {
            setCategoryLoading(false);
        });
    }, []);
    
    useEffect(() => {
        // prop的account改变,重新初始化,再将数据覆盖
        let data = {...initFormData, date_time: moment(initFormData.date_time)}

        if (account) {
            data = {...data, ...account, date_time: moment(account.date_time)}
        }
        // console.log(data)
        setFormData({...data})
    }, [account])

    // form数据绑定
    useEffect(() => {
        form.setFieldsValue(formData)
    }, [formData]);

    const [category, setCategory] = useState<ICategory[]>([]);


    const handleOk = () => {
        // 提交添加
        form.validateFields()
        .then(async (val) => {
            // console.log(val)
            props.submitFrom({...val, account_id: formData.account_id});
        })
    }


    return (
        <Form
            labelCol={{span: 4}}
            form={form}
            initialValues={formData}
            scrollToFirstError={true}
            preserve={false}
            validateTrigger={['onBlur', 'onChange']}
        >
            <Form.Item name="amount" hasFeedback label="金额" rules={[
                { required: true, message: '请输入数字金额', type: 'number' }
            ]}>
                <InputNumber style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="date_time" hasFeedback label="日期" rules={[
                { required: true, message: '请选择日期' }
            ]}>
                <DatePicker locale={locale} />
            </Form.Item>
            {/* valurPropName 和 defaultChecked 不论使用那个都会有警告, 但不影响执行 */}
            <Form.Item valuePropName={formData.account_type === AccountType.expend ? 'checked' : 'unchecked'} name="account_type" label="类型">
                <Switch defaultChecked={formData.account_type === AccountType.expend} checkedChildren={AccountType.expend} unCheckedChildren={AccountType.income} />
            </Form.Item>
            <Form.Item name="category_id" label="分类" rules={[
                { 
                    required: true, 
                    message: '请选择分类', 
                    validator(rule, v) {
                        if (v === 0) {
                            return Promise.reject('请选择分类')
                        }
                        return Promise.resolve()
                    }
                }
            ]}>
                <Radio.Group>
                    {
                        categoryLoading ? 
                            <Spin className="loading" /> : ''
                    }
                    {
                        category.map(item => <Radio.Button key={item.category_id} value={item.category_id}>{item.category_name}</Radio.Button>)
                    }
                </Radio.Group>
            </Form.Item>
            <Form.Item name="notes" hasFeedback label="备注" 
                rules={[
                    { max: 200 }
                ]}
            >
                <Input.TextArea rows={4}  />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16, push: 6 }}>
                <Space>
                    <Button onClick={() => props.cancel()}>取消</Button>
                    <Button type="primary" onClick={handleOk}>提交</Button>
                </Space>
            </Form.Item>
        </Form>
    )
}


export default AccountCommit;

